package com.sdgakj.service.orderFlow;

import com.sdgakj.entity.OrderFlow;
import com.sdgakj.repository.OrderFlowDao;
import com.sdgakj.utils.SchoolSearchFilter;
import com.sdgakj.utils.SchoolSpecifications;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Component
@Transactional
public class OrderFlowService
{
	
	@Autowired
    private OrderFlowDao orderFlowDao;
	
    public List<OrderFlow> getAllList()
    {
        return (List<OrderFlow>) orderFlowDao.findAll();
	}
	
    public OrderFlow getOrderFlowById(Long id)
    {
        return orderFlowDao.findOne(id);
	}
	
	/**
	 * 保存
	 * @param entity
	 */
    public void saveOrderFlow(OrderFlow entity)
    {
        orderFlowDao.save(entity);
	}
	
	/**
	 * 更新
	 * @param entity
	 */
    public void updateOrderFlow(OrderFlow entity)
    {
        orderFlowDao.save(entity);
	}

    public Page<OrderFlow> getOrderFlowByPage(Map<String, Object> searchParams,
            int pageNumber, int pageSize, String sortType)
    {
		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
        Specification<OrderFlow> spec = buildSpecification(searchParams);
        return orderFlowDao.findAll(spec, pageRequest);
	}	
	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize,String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		}
		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}

	/**
	 * 创建动态查询条件组合.
	 */
    private Specification<OrderFlow> buildSpecification(Map<String, Object> searchParams)
    {
        Map<String, SchoolSearchFilter> filters = SchoolSearchFilter.parse(searchParams);
        Specification<OrderFlow> spec = SchoolSpecifications.bySearchFilter(filters.values(),
                OrderFlow.class);
		return spec;
	}
	
}
